package com.programming.movie.manager.impl;

import java.util.List;

import com.programming.common.exception.DAOException;
import com.programming.common.exception.ManagerException;
import com.programming.common.page.Page;
import com.programming.movie.dao.SeachDAO;
import com.programming.movie.dataobject.SeachInfo;
import com.programming.movie.manager.SeachManager;

public class SeachManagerImpl implements SeachManager {
	private SeachDAO seachDAO;

	public void setSeachDAO(SeachDAO seachDAO) throws ManagerException {
		this.seachDAO = seachDAO;
	}

	public boolean delete(Long id) throws ManagerException {
		try {
			this.seachDAO.delete(id);
			return true;
		} catch (DAOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public SeachInfo getById(Long id) throws ManagerException {
		try {
			return this.seachDAO.getById(id);		
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Page query(SeachInfo seachInfo, int start, int limit) throws ManagerException {
		try {
			return this.seachDAO.query(seachInfo, start, limit);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<SeachInfo> queryList(SeachInfo seachInfo) throws ManagerException {
		try {
			return this.seachDAO.queryList(seachInfo);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public boolean save(SeachInfo seachInfo) throws ManagerException {
		if (seachInfo.getId() != null) {
			try {
				this.seachDAO.update(seachInfo);
			} catch (DAOException e) {
				e.printStackTrace();
				return false;
			}
		} else {
			try {
				this.seachDAO.insert(seachInfo);
			} catch (DAOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	@Override
	public void getfindKeyWord(String keyWord) throws ManagerException {
		SeachInfo seachInfo = new SeachInfo();
		seachInfo.setKeyWord(keyWord);
		try {
			List<SeachInfo> list = this.seachDAO.queryList(seachInfo);
			if (list.size() == 1) {
				SeachInfo seach = list.get(0);
				seach.setCountSeach(seach.getCountSeach() + 1);
				this.seachDAO.update(seach);
			} else {
				SeachInfo seach = new SeachInfo();
				seach.setKeyWord(keyWord);
				seach.setCountSeach(1L);
				seachDAO.insert(seach);
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}
	}

}
